import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/network_utils.dart';
import '../../models/order_list_model.dart';
import '../../components/toast_utils.dart';
import '../view/pay_bottpm_view.dart';
import '../../login/controller/webview.dart';
import '../view/pay_cell_view.dart';
import '../../components/overlay_view.dart';
import '../../models/order_detail_model.dart';
import '../../manger/global_config.dart';
// import 'package:uni_links/uni_links.dart';
import 'package:app_links/app_links.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../login/controller/webview_pay.dart';
import 'dart:async';
import 'dart:io'; // 引入 dart:io 库
import '../../models/adress_info_model.dart';
import '../../services/adress_manger.dart';
import 'package:ninetyfour/manger/user_manger.dart';
import '../view/pay_adress_view.dart';
import '../../login/controller/adresss_pop_view.dart';
import '../../manger/umevent_utils.dart';
import '../../manger/checkspu_utils.dart';
import '../../class/view/webView_maskview.dart';

class OrderPayPage extends StatefulWidget {
  final String orderId;
  final int spuId;
  const OrderPayPage({super.key, required this.orderId, required this.spuId});

  @override
  State<OrderPayPage> createState() => _OrderPayPageState();
}

class _OrderPayPageState extends State<OrderPayPage> with WidgetsBindingObserver{
  final _scrollController = ScrollController();

  PayListModel? shopPayment; // 支付方式ID
  int selectIndex = 0; // 选中的索引
  double priceFee = 0.0;
  double shouxucount = 0.0;
  String symbol = "";
  String newOrderId = "";  // 订单ID
  List<PayListModel>? payList;
  DateTime? lastClickTime; // 记录上次点击时间，用于防抖
  bool isPushSafri = false; // 是否是推送过来的
  StreamSubscription? _sub;
  late final AppLinks _appLinks;
  List<AdressInfo> adressInfo = []; // 地址信息列表
  List<AdressInfo> adressInfo2 = []; // 需要显示的地址信息列表 0 卡支付 1本地支付的账单地址
  bool showAddressView = false;
  String urls = '';
  int selectASddress = 0; // 选中的账单ID
  bool isShowAddress = false; // 是否显示地址信息

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); // 监听生命周期

    WidgetsBinding.instance.addPostFrameCallback((_) {
      loadAddressData();
    });
    initUniLinks();
  }

  void initUniLinks() async {
    _appLinks = AppLinks();

    try {
      // 冷启动处理（首次启动 app 时的 deep link）
      final Uri? initialUri = await _appLinks.getInitialLink();
      if (initialUri != null) {
        handleIncomingLink(initialUri.toString());
      }
    } catch (e) {
      print('getInitialAppLink error: $e');
    }

    // 运行时监听（app 运行中收到 deep link）
    _sub = _appLinks.uriLinkStream.listen(
      (Uri uri) {
        handleIncomingLink(uri.toString());
      },
      onError: (err) {
        print("DeepLink error: $err");
      },
    );
  }

  void handleIncomingLink(String link) {
    final uri = Uri.parse(link);
    final token = uri.queryParameters["Apptokenc"];
    UserInfos.shared.productToken = token?? "";

  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // 移除监听
    super.dispose();
  }
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // App 从后台回到前台（包括从浏览器返回）
      handleAppResume();
    }
  }

  void handleAppResume() {
    if (isPushSafri) {
      isPushSafri = false;
      OverlayView.shared.show(context, newOrderId);
    }
  }

  Future<void> payment() async {
    if (mounted) {
      ToastUtils.showLoadingToast(context);
    }
    try {
      final response = await NetworkUtils.post(
        RequestCmd.checkout,
        body: {"orderId": widget.orderId,"paymentMethod":"","num":1,"itemId":widget.spuId},
      );

      final model = ConfirmInfoModel.fromJson(response);
      if (model.code == 200) {
        if (mounted) {
          setState(() {
            payList = model.data?.paymentList;
          });
          loadData("1");
        }
      } else {
        ToastUtils.dismissLoadingToast();
        ToastUtils.showCenterToast(context, model.msg);
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print(e);
    }

  }

  void loadAddressData() async {
    final manager = AdressInfoManager();
    final success2 = await manager.loadInfoData();
    if (success2.success) {
      setState(() {
        adressInfo = success2.adressInfo ?? [];
      });
    } 
    payment();
  }

  loadData(String type) async{
    try {
      final response = await NetworkUtils.post(
        RequestCmd.cashier,
        body: {"orderId": widget.orderId, "paymentMethod": shopPayment == null ? "" : shopPayment!.shopPaymentId},      
      );
      ToastUtils.dismissLoadingToast();
      final model = CashierModel.fromJson(response);
      if (model.code == 200) {
          final cashierData = model.data;
          if (mounted) {
            setState(() {
              shouxucount = double.tryParse(cashierData?.processFee ?? '0.0') ?? 0.0;
              symbol = cashierData?.symbol?? "";
              priceFee = double.tryParse(cashierData?.paymentMoney?? '0.0')?? 0.0; 
              
            });
            if (type == "1") {
              if (cashierData?.paymentMethod != null) {
                checkPaymentMethod(cashierData!.paymentMethod);
              }
            }    
          }       
      }
    } catch (e) {
      print(e);
    }
  }

  void createOrder() async {
      UmengEvent.trackEvent("orderdetail_payment_click","订单详情页，点击支付按钮",shopPayment!.shopPaymentId.toString());
      if (shopPayment!.needAddress == 1 ) {
        if (adressInfo2.isEmpty) {
          ToastUtils.showCenterToast(context,  AppLocalizations.of(context)!.newcreateAddress);
          return;
        }
        cerateOrderForAddress();
      } else if (shopPayment!.shopPaymentId == 22 || shopPayment!.shopPaymentId == 42) {
        useePayment();
      } else {
        ToastUtils.showLoadingToast(context);
        try {
          final response = await NetworkUtils.post(
            RequestCmd.create,
            body: {"orderId": widget.orderId,"paymentMethod":shopPayment!.shopPaymentId},
          );
          ToastUtils.dismissLoadingToast();
          if (shopPayment!.shopPaymentId == 24 || shopPayment!.shopPaymentId == 25 || shopPayment!.shopPaymentId == 44 || shopPayment!.shopPaymentId == 45) {
            final model = OrderThreeModel.fromJson(response);
            if (model.code == 200) {
              if (model.data?.orderId != null) {
                newOrderId = model.data!.orderId;
                pushWebView2(model.data!);
              } else {
                print('orderId is null');
              }
            } else {
              ToastUtils.showCenterToast(context, model.msg);
            }
          }else {
            final model = OrderModel.fromJson(response);
            if (model.code == 200) {
              if (model.data?.orderId != null) {
                newOrderId = model.data!.orderId;
              } 
              if (model.data?.redirectUrl != null) {     
                openLaunchUrl(model.data!.redirectUrl);
              } else {
                OverlayView.shared.show(context,newOrderId);
              }
            } else {
              ToastUtils.showCenterToast(context, model.msg);
            }
          }

        } catch (e) {
          ToastUtils.dismissLoadingToast();
          print(e);
        }
      }
  }

  void cerateOrderForAddress() async {
    final adressId = adressInfo[selectASddress].id.toString();
    ToastUtils.showLoadingToast(context);
    try {
      final response = await NetworkUtils.post(
        RequestCmd.create,
        body: {"orderId": widget.orderId, "paymentMethod": shopPayment!.shopPaymentId, "billingId": adressId},
      );
      ToastUtils.dismissLoadingToast();
      final model = OrderThreeModel.fromJson(response);
      if (model.code == 200) {
        if (model.data?.orderId != null) {
          newOrderId = model.data!.orderId;
          if ((model.data?.redirectUrl ?? '').isNotEmpty) {
              openLaunchUrl(model.data?.redirectUrl?? "");
            } else {
              pushWebView2(model.data!);
            }
        } else {
          print('orderId is null');
        }
      } else {
        ToastUtils.showCenterToast(context, model.msg);
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print(e);
    }
  }

  void useePayment() async {
    Map<String, dynamic> useepayMsg = {
      "email": "",
      "firstName": "",
      "lastName": "",
    };
    ToastUtils.showLoadingToast(context);
    var param = {'orderId': widget.orderId,
      "paymentMethod": shopPayment!.shopPaymentId,"useepayMsg":useepayMsg};

    final response = await NetworkUtils.get(
      RequestCmd.getUseePayData,
      params: param,
    );
    ToastUtils.dismissLoadingToast();
    final model = UseepayData.fromJson(response);
    if (model.code == 200) {
      pushWebView(param, model.data);
    } else {
      pushWebView(param);
    }

    ToastUtils.dismissLoadingToast();
  }

  void pushWebView(Map<String, dynamic> params, [UseepayModel? model]) {
    var price = priceFee.toStringAsFixed(2);
    final url = UrlConfig.buildUrlString(price, model,context);
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context2) => WebViewPage(
          title: AppLocalizations.of(context)!.cardpayment,
          url: url,
          oredrArrays: params,
          onOrderIdReceived: (receivedOrderId) {
            setState(() {
              newOrderId = receivedOrderId;
              if (newOrderId.isNotEmpty) {                
                OverlayView.shared.show(context,newOrderId);
              }
            });
          },
        ),
      ),
    );  
  }

  void pushWebView2(OrderInfoThreeModel model) {
    var finalUrlString = "";
      final String platformType = Platform.isIOS ? 'iOS' : 'Android';
      var price = priceFee.toStringAsFixed(2);
    if (shopPayment!.shopPaymentId == 24 || shopPayment!.shopPaymentId == 44) {
      finalUrlString = "${UrlConfig.baseUrl}${UrlConfig.getTabsParam(context)}/appleAppPay?intent_id=${model.payInfo!.id}&client_secret=${model.payInfo!.clientSecret}&currency=${model.payInfo!.currency}&terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&orderId=${model.orderId}&price=$price";
    } else if (shopPayment!.shopPaymentId == 25 || shopPayment!.shopPaymentId == 45) {
      finalUrlString = "${UrlConfig.baseUrl}${UrlConfig.getTabsParam(context)}/appGooglepay?intent_id=${model.payInfo!.id}&client_secret=${model.payInfo!.clientSecret}&currency=${model.payInfo!.currency}&terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&orderId=${model.orderId}&price=$price";
      openLaunchUrl(finalUrlString);
      return;
    }
    else {
      final adressId = adressInfo[selectASddress].id.toString();
      finalUrlString = "${UrlConfig.baseUrl}${UrlConfig.getTabsParam(context)}/appAirwallex?intent_id=${model.payInfo!.id}&client_secret=${model.payInfo!.clientSecret}&currency=${model.payInfo!.currency}&terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&orderId=${model.orderId}&price=$price&billingApp_id=$adressId";
    }
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context2) => WebViewPayPage(
          url: finalUrlString,
          onOrderIdReceived: (receivedOrderId) {
            OverlayView.shared.show(context,newOrderId);
          },
        ),
      ),
    ); 
  }

  void openLaunchUrl(String url) async{
    isPushSafri = true;
    await launchUrl(
      Uri.parse(url),
      mode: LaunchMode.externalApplication, // 👈 强制使用 Safari 打开
    );
  }


  checkPaymentMethod(int paymentMethod){
    if(payList != null && payList!.isNotEmpty) {
      for(int i = 0; i < payList!.length; i++) {
        if(payList![i].shopPaymentId == paymentMethod) {
            setState(() {
              selectIndex = i;
              shopPayment = payList![i];
            });

            if (shopPayment!.needAddress == 1) {
              showAddress();
            }
          break;
        }
      }
    }
  }

  void showAddress(){
    if (shopPayment!.localPayment == 0) {
      setState(() {
         adressInfo2 = adressInfo.where((item) => item.type == 0).toList();
      });
    } else {
      setState(() {
         adressInfo2 = adressInfo.where((item) => item.type == 1).toList();
      });
    }
    setState(() {
      isShowAddress = true;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_scrollController.hasClients) {
          _scrollController.animateTo(
            _scrollController.position.maxScrollExtent,
            duration: Duration(milliseconds: 300),
            curve: Curves.easeOut,
          );
        }
      });
    });
  }

  void changeAddress(int index) {
    selectASddress = index;
    final String platformType = Platform.isIOS ? 'iOS' : 'Android';
    final adressId = adressInfo[index].id.toString();
    String url = "${UrlConfig.baseUrl}/appBilling2?terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&billingApp_id=$adressId&type=${shopPayment!.localPayment}";
    loadHtml(url);
  }

  void onAddAddress() {
    final String platformType = Platform.isIOS ? 'iOS' : 'Android';
    String url = "${UrlConfig.baseUrl}/appBilling2?terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&type=${shopPayment!.localPayment}";
    loadHtml(url);
  }

  loadHtml(String url) {
    setState(() {
      urls = url;
      showAddressView = true;
    });
  }

  hideAddressView() {
    setState(() {
      showAddressView = false;
    });
  }

  @override
@override
Widget build(BuildContext context) {
  return Stack(
    children: [
      /// 主页面 Scaffold
      Scaffold(
        appBar: AppBar(
          toolbarHeight: 40,
          title: Text(
            AppLocalizations.of(context)!.checkstand,
            style: const TextStyle(fontSize: 17),
          ),
        ),
        body: SingleChildScrollView(
          controller: _scrollController,
          child: Column(
            children: [
              // 第一部分
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '$symbol$priceFee',
                      style: TextStyle(
                        color: Color(0xFFF61F03),
                        fontSize: 25,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 8),
                    Text(
                      '${AppLocalizations.of(context)!.handlingFee}: $symbol$shouxucount',
                      style: TextStyle(
                        color: Color(0xFF666666),
                        fontSize: 13,
                      ),
                    ),
                  ],
                ),
              ),

              // 第二部分：支付方式
              if (payList != null)
                Container(
                  margin: const EdgeInsets.symmetric(horizontal: 15),
                  decoration: BoxDecoration(
                    color: const Color(0xFFECEDFF),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: Row(
                          children: [
                            Image.asset(
                              'assets/images/payicon1.png',
                              width: 24,
                              height: 24,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              AppLocalizations.of(context)!.paymentmethod,
                              style: TextStyle(
                                color: const Color(0xFF000000),
                                fontSize: 14,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        color: Colors.white,
                        child: ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: payList!.length,
                          itemBuilder: (context, index) {
                            return PayCellView(
                              onShowAuthTips: () {
                                showDialog(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return Dialog(
                                      backgroundColor: Colors.transparent,
                                      child: WebViewMaskView(
                                        url: UrlConfig.fuinURL(context), // 这里放入你需要加载的 URL
                                        onDismiss: () {
                                          Navigator.pop(context); // 点击外部区域时退出 WebView
                                        },
                                      ),
                                    );
                                  },
                                );
                              },
                              model: payList![index],
                              isSelected: index == selectIndex,
                              onTap: () {
                                final currentTime = DateTime.now();
                                if (lastClickTime != null &&
                                    currentTime.difference(lastClickTime!).inMilliseconds < 500) {
                                  ToastUtils.showCenterToast(context, '操作频繁');
                                  return;
                                }
                                lastClickTime = currentTime;

                                setState(() {
                                  selectIndex = index;
                                  shopPayment = payList![index];
                                });
                                if (payList![index].needAddress == 1) {
                                  showAddress();
                                } else {
                                  setState(() {
                                    isShowAddress = false;
                                  });
                                }
                                loadData("2");
                              },
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),

              // 第三部分：地址信息
              if (isShowAddress)
                PayAddressView(
                  adressInfo: adressInfo2,
                  onCLickAdd: () {
                    onAddAddress();
                  },
                  onChangeAddress: (value) {
                    changeAddress(value);
                  },
                ),

              // 第四部分：底部说明
              PayBottomView(
                onTapLink: (url) {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => WebViewPage(
                        title: AppLocalizations.of(context)!.news,
                        url: url,
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
        bottomNavigationBar: Container(
          height: 90,
          color: Colors.white,
          padding: const EdgeInsets.symmetric(horizontal: 15),
          child: Container(
            padding: const EdgeInsets.only(top: 15, bottom: 30),
            child: SizedBox(
              height: 44,
              width: double.infinity,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF5D60EF),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(22),
                  ),
                ),
                onPressed: () {
                  createOrder();
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      'assets/images/order_icon6.png',
                      width: 20,
                      height: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      AppLocalizations.of(context)!.submitOrder,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),

      /// ⬇ Address 弹窗
      if (urls.isNotEmpty)
        Positioned.fill(
          child: IgnorePointer(
            ignoring: !showAddressView,
            child: AnimatedOpacity(
              opacity: showAddressView ? 1.0 : 0.0,
              duration: Duration(milliseconds: 200),
              child: AddresssPopView(
                url: urls,
                visible: showAddressView,
                viewHeight: 550,
                onSaveSuccess: () {
                  hideAddressView();
                  loadAddressData(); // 刷新地址数据
                },
                onDismiss: hideAddressView,
              ),
            ),
          ),
        ),
    ],
  );
}

}